import { Component, OnInit, Injector, ViewChild } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Table } from 'primeng/table';
import { Paginator, LazyLoadEvent } from 'primeng/primeng';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import {
    ListDtoExtensionsItem,
    Stock_BillListDto,
    Stock_OutToolItemListDto,
    GetStock_AuditInputDto,
    StockZT_CancelBillServiceProxy,
    StockZT_ReturnBillItemServiceProxy,
    ComboboxItemDto,
    SessionServiceProxy,
} from '@shared/service-proxies/stock-service-proxies';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';

@Component({
    templateUrl: './market-return.component.html',
    animations: [appModuleAnimation()],
    selector: 'marketreturn'
})
export class MarketReturnComponent extends AppComponentBase {
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    @ViewChild('detailDataTable') detailDataTable: Table;
    @ViewChild('detailPaginator') detailPaginator: Paginator;

    // filters
    deptFilter = '';
    taskNumFilter = '';
    drawingNumFilter = '';
    materialCodeFilter = '';
    materialNameFilter="";
    certificationNumFilter = '';
    reCheckFilter = '';
    supplierFilter = '';
    warehouseNameFilter = '';
    billcode = '';

    userDataPermissions;
    selectedDepts;
    extensions: Array<ListDtoExtensionsItem>;
    detialExtensions: Array<ListDtoExtensionsItem>;

    detailPrimengTableHelper: PrimengTableHelper;
    selectedBill: Stock_BillListDto;
    auditDto: GetStock_AuditInputDto;
    purchaseOption;
    selectedPurchaseType;
    roomOption;
    selectedWareHouse;
    billStatusOptions = [
        { label: '全部', value: undefined },
        { label: '新建', value: '新建' },
        { label: '已提交', value: '已提交' },
        { label: '已出库', value: '已出库' }
    ];
    billstatus = '';
    selectedBillItem = new Stock_OutToolItemListDto();

    constructor(
        injector: Injector,
        private _billService: StockZT_ReturnBillItemServiceProxy,
        private _cancelBillSerive :StockZT_CancelBillServiceProxy,
        private _base_SessionServiceProxy: SessionServiceProxy
    ) {
        super(injector);
        this.detailPrimengTableHelper = new PrimengTableHelper();
    }

    ngOnInit(): void {        
        /* this._userDataPermissionServiceProxy.getUserDataPermissions('Base_Bill').subscribe(result => {
            this.userDataPermissions = result.items.map(e => {
                return {
                    label: e.displayText,
                    value: e
                };
            });

             this._base_SessionServiceProxy.getCurrentDept().subscribe(result => {             let ssData = new ComboboxItemDto();             ssData.value = result.value;             ssData.isSelected = false;             ssData.displayText = result.label;             let ss: ComboboxItemDto[] = [ssData];             this.selectedDepts = ss;         });

            this._RoomServiceProxy.getRoomListByDepts(result.items, '市采物资库', '').subscribe(result2 => {
                this.roomOption = result2.items.map(e => {
                    return {
                        label: e.displayText,
                        value: e
                    };
                });
                this.selectedWareHouse = result2.items;
                this.getBills();
            });
        });
        this._intoBillItemService.getPurchaseTypeOutByDataItem().subscribe(result1 => {
            this.purchaseOption = result1.map(e => {
                return {
                    label: e.label,
                    value: e
                };
            });

            this.selectedPurchaseType = result1;
        }); */
        this._cancelBillSerive.loadCancelMarket().subscribe(result=>{
            this.userDataPermissions = result.userDataPermissions.items.map(e => {
                return {
                    label: e.displayText,
                    value: e
                };
            });
            this.selectedDepts = result.userDataPermissions.items;

            this.purchaseOption = result.purchaseTypeOption.map(e => {
                return {
                    label: e.label,
                    value: e
                };
            });

            this.selectedPurchaseType = result.purchaseTypeOption;
            this._base_SessionServiceProxy.getCurrentDept().subscribe(result => {
                let ssData = new ComboboxItemDto();
                ssData.value = result.value;
                ssData.isSelected = false;
                ssData.displayText = result.label;
                let ss: ComboboxItemDto[] = [ssData];
                this.selectedDepts = ss; 
            });
            this.getBills();
        });
    }

    getBills(event?: LazyLoadEvent, resetpage?: boolean) {
        if (!this.selectedDepts) {
            return;
        }
        if (this.primengTableHelper.shouldResetPaging(event) || event.first == undefined) {
            if(resetpage == undefined) {
                this.paginator.changePage(0);
                return;
            }
        }

        this.primengTableHelper.showLoadingIndicator();

        this._billService
            .getReturnMarketBaseListExtension(
                undefined,
                undefined,
                this.materialCodeFilter,
                this.materialNameFilter,
                this.billcode,
                this.billstatus,
                this.selectedDepts,
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            )
            .subscribe(result => {
                this.extensions = result.items;
                this.primengTableHelper.totalRecordsCount = result.stock_CancelMarketBaseList.totalCount;
                this.primengTableHelper.records = result.stock_CancelMarketBaseList.items;
                this.primengTableHelper.hideLoadingIndicator();
                this.detailPrimengTableHelper.totalRecordsCount = 0;
                this.detailPrimengTableHelper.records = null;
                this.selectedBill = null;
                this.selectedBillItem = null;
            });
    }
    submitBill() {
        if (this.selectedBill.f_BillStatus != '新建') {
            this.message.warn('已提交或已审核！');
            return;
        }
        if (!this.selectedBill) {
            return;
        }
        if (this.detailPrimengTableHelper.totalRecordsCount <= 0) {
            this.message.warn('没有添加明细，不能提交');
            return;
        }
        this.auditDto = new GetStock_AuditInputDto();
        this.auditDto.id = this.selectedBill.id;
        this.message.confirm('确认提交？', isConfirmed => {
            if (isConfirmed) {
                this._billService
                    .submitToolReturnBillBase(this.selectedBill.id)
                  .subscribe(() => {
                       
                        this.notify.success(this.l('提交成功'));
                        /* this.getBills(undefined, true); */
                        this.selectedBill.f_BillStatus = '已提交';
                        this.primengTableHelper.hideLoadingIndicator();
                    });

            }
        });
    }
    postBill() {
        if (!this.selectedBill) {
            return;
        }
        if (this.selectedBill.f_BillStatus != '已提交') {
            this.message.warn('只有已提交的单据可以过账，本单据不能过账！');
            return;
        }
       
        this.message.confirm('确认过账该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .postToolReturnBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('过账成功'));
                        this.selectedBill.f_BillStatus = "已出库";
                        this.selectedBill.f_Posted = "已过账";
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }
    sendBackBill() {  
        if (!this.selectedBill) {
            return;
        }      
        if (this.selectedBill.f_Posted == '已过帐') {
            this.message.warn('已过账，不能退回！');
            return;
        }
        if(this.selectedBill.f_BillStatus == "已提交"){     
            this.message.confirm('确认退回该条数据吗？', isConfirmed => {
                if (isConfirmed) {
            this.primengTableHelper.showLoadingIndicator();
            this._billService
                .sendBackToolReturnBillBase(this.selectedBill.id)
                .pipe(
                    finalize(() => {
                    
                    this.primengTableHelper.hideLoadingIndicator();
                    })
                )
                .subscribe(() => {
                    this.notify.success(this.l('退回成功'));                    
                    this.selectedBill.f_BillStatus = "新建"; 
                    this.selectedBill.f_Posted = "未过账"; 
                    this.getBillItems();
                    this.primengTableHelper.hideLoadingIndicator();
                });
                }
            });
        }else{
            this.message.warn('只有已提交的单据可以退回，本单据不能退回！');
            return;
        }
    }

    reloadData(event) {
        if (event == null || event == undefined) {
            this.getBills();
        } else {
            this.getBillItems();
        }
    }
    getBillItems(event?: LazyLoadEvent) {
        if (!this.selectedBill) {
            return;
        }
        if (this.detailPrimengTableHelper.shouldResetPaging(event)) {
            this.detailPaginator.changePage(0);

            return;
        }

        this.primengTableHelper.showLoadingIndicator();

        this._billService
            .getReturnMarketItemListExtension(
                this.selectedBill.id,
                this.detailPrimengTableHelper.getSorting(this.detailDataTable),
                this.detailPrimengTableHelper.getMaxResultCount(this.detailPaginator, event),
                this.detailPrimengTableHelper.getSkipCount(this.detailPaginator, event)
            )
            .subscribe(result => {
                this.detialExtensions = result.items;
                this.detailPrimengTableHelper.totalRecordsCount = result.stock_OutMarketItemList.totalCount;
                this.detailPrimengTableHelper.records = result.stock_OutMarketItemList.items;
                this.primengTableHelper.hideLoadingIndicator();

                this.selectedBillItem = null;
            });
    }

    deleteBill() {
        if (!this.selectedBill) {
            return;
        }

        this.message.confirm('确认删除该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .deleteReturnBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('SuccessfullyDeleted'));
                        this.getBills();
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }

    deleteBillItem() {
        if (!this.selectedBillItem) {
            return;
        }

        this.message.confirm('确认删除该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .deleteReturnBillItem(this.selectedBillItem.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('SuccessfullyDeleted'));
                        this.getBillItems();
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }
}
